/* NOTICE
 
    Jim - the Java Image Manager, copyright (c) 2005 - 2007 Grant Gardner 
 
    Jim is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    Jim is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
  
    In addition, as a special exception, you are permitted to link this code
    with the 3rd party libraries required to compile this file and to
    distribute a linked combination including them. You must obey the
    GNU General Public License in all respects for all of the code except for
    those 3rd party libraries that are licenced under terms incompatible with the
    GNU General Public License.  
 
 
 NOTICE */

package au.com.lastweekend.jim.imagebase;

import java.awt.image.BufferedImage;
import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

import org.apache.log4j.Logger;

import au.com.lastweekend.jim.io.exif.ExifDirectory;
import au.com.lastweekend.jim.io.exif.ThumbnailTiffDirectory;
import au.com.lastweekend.jim.io.exif.TiffDirectory;
import au.com.lastweekend.jim.io.jpeg.JpegReader;
import au.com.lastweekend.jim.io.jpeg.read.MetadataOnlySegmentReaderRegistry;
import au.com.lastweekend.jim.io.metadata.Directory;
import au.com.lastweekend.jim.io.metadata.Metadata;
import au.com.lastweekend.jim.io.metadata.MetadataException;
import au.com.lastweekend.jim.io.metadata.Tag;

/**
 * @author grant@lastweekend.com.au
 * @version $Id: ImageInfo.java,v 1.8 2006/03/01 09:52:04 ggardner Exp $
 */
public final class ImageInfo {

    private ImageBase imageBase;
    private File file;
    private Metadata metadata = null;
    private List<Tag> tags = null;
    private boolean loaded = false;
    private static final Logger LOG = Logger.getLogger(ImageInfo.class);
    private BufferedImage thumbnail;

    protected ImageInfo(ImageBase imageBase, File file) {

        this.imageBase = imageBase;
        this.file = file;
    }

    /**
     * @param filename
     */
    protected ImageInfo(ImageBase imageBase, String filename) {

        this(imageBase, new File(filename));
    }

    protected ImageInfo(ImageBase imageBase, File fileKey, ImageBaseDirectory imageDirectory) {

        this(imageBase, fileKey);
        holdImageDirectory(imageDirectory);
    }

    protected void holdImageDirectory(ImageBaseDirectory imageDirectory) {

        // The image directory will be found later, but we'll hold on to it
        // here, so it doesn't get chucked out of the cache.
        metadata = new Metadata();
        metadata.addDirectory(imageDirectory);
    }

    protected void load() {

        if (!isLoaded()) {
            File imageFile = getFile();
            metadata = new Metadata();

            // this will add the imagebase data to metadata if found.
            ImageBaseDirectory imageBaseDirectory = findImageBaseDirectory(imageFile);

            if (imageFile.exists()) {
                if (imageBaseDirectory != null) {
                    imageBaseDirectory.addFile(imageFile);
                }
                loadMetadata(imageFile);
            }

            notifyLoaded();

        }

    }

    protected Metadata getMetadata() {

        return metadata;
    }

    protected ImageBaseDirectory findImageBaseDirectory(File imageFile) {

        // ImageBase metadata
        ImageBaseDirectory imageBaseDirectory = getImageBase().findDirectory(imageFile.getName());
        if (imageBaseDirectory != null) {

            addImageBaseDirectory(imageBaseDirectory);

        }
        return imageBaseDirectory;
    }

    private void notifyLoaded() {

        loaded = true;
    }

    private boolean isLoaded() {

        return loaded;
    }

    public File getFile() {

        return file;
    }

    public List<Tag> getAllTags() {

        load();
        if (tags != null) {
            return tags;
        }

        tags = new ArrayList<Tag>();
        for (Iterator<Directory> iter = metadata.getDirectoryIterator(); iter.hasNext();) {
            Directory directory = iter.next();
            for (Iterator<Tag> tagIterator = directory.getTagIterator(); tagIterator.hasNext();) {
                Tag tag = tagIterator.next();
                tags.add(tag);
            }
        }
        return tags;
    }

    public boolean hasImageBaseDirectory() {

        load();
        return metadata.containsDirectory(ImageBaseDirectory.class);
    }

    private void addImageBaseDirectory(ImageBaseDirectory directory) {

        if (metadata == null) {
            holdImageDirectory(directory);
        } else {
            metadata.addDirectory(directory);
            tags = null;
        }
    }

    /**
     * java ImageInfo <filename>Prints to standard out, the tag information contained within a JPEG file.
     * 
     * @param args
     */
    @SuppressWarnings({"PMD.SystemPrintln", "PMD.AvoidPrintStackTrace"})
    public static void main(String[] args) {

        ImageBase imageBase = new NullImageBase();

        for (int a = 0; a < args.length; a++) {
            String filename = args[a];
            System.out.println("BEGIN: Tags for " + filename);
            ImageInfo imageInfo = new ImageInfo(imageBase, filename);

            List<Tag> tagList = imageInfo.getAllTags();

            for (Iterator<Tag> iter = tagList.iterator(); iter.hasNext();) {
                Tag tag = iter.next();
                try {
                    System.out.println(tag.getDirectoryName() + ":" + tag.getTagName() + ":" + tag.getDescription());
                } catch (MetadataException e) {
                    e.printStackTrace();
                }

            }
            System.out.println("END: Tags for " + filename);
        }

    }

    Set<String> getKeywordSet() {

        ImageBaseDirectory imageDirectory = getImageBaseDirectory();
        if (imageDirectory == null) {
            return Collections.emptySet();
        } else {
            return (imageDirectory).getKeywords();
        }
    }

    private ImageBaseDirectory getImageBaseDirectory() {

        load();
        return (ImageBaseDirectory) metadata.getDirectory(ImageBaseDirectory.class);
    }

    /*
     * @see au.com.lastweekend.jim.imagebase.KeywordItem#hasKeyword(java.lang.String)
     */
    public boolean hasKeyword(String keyword) {

        Set<String> keywordSet = getKeywordSet();
        if (keywordSet == null) {
            return false;
        }
        return keywordSet.contains(keyword);
    }

    /*
     * @see au.com.lastweekend.jim.imagebase.KeywordItem#updateKeywordSelection(java.lang.String, boolean)
     */
    public void updateKeywordSelection(String keywordString, boolean selected) {

        Set<String> keywordSet = new HashSet<String>(getKeywordSet()); // unmodifiable

        if (selected) {
            keywordSet.add(keywordString);
        } else {
            keywordSet.remove(keywordString);
        }

        (getImageBaseDirectory()).setKeywords(keywordSet);

    }

    protected ImageBase getImageBase() {

        return imageBase;
    }

    /**
     * 
     */
    public void reset() {

        // Note we don't reset _metadata here, because the directories it
        // contains are possibly held in soft caches
        // it will be reset on load..
        loaded = false;
        tags = null;
        thumbnail = null;

    }

    public boolean isLost() {

        return !getFile().exists();
    }

    protected void loadMetadata(File imageFile) {

        Metadata metadata = getMetadata();

        metadata.addDirectory(getImageFileDirectory(imageFile));
        try {

            JpegReader reader = new JpegReader(new MetadataOnlySegmentReaderRegistry());
            reader.readMetadata(metadata, imageFile);

        } catch (Exception e) {
            LOG.warn("Exception loading image info ", e);
        }
    }

    private Directory getImageFileDirectory(File imageFile) {

        return new ImageFileDirectory(imageFile);
    }

    public boolean hasThumbnail() {

        load();
        return (metadata.containsDirectory(ThumbnailTiffDirectory.class));
    }

    public BufferedImage getThumbnail() {

        if (hasThumbnail() && thumbnail == null) {
            ThumbnailTiffDirectory thumbnailDir = (ThumbnailTiffDirectory) metadata.getDirectory(ThumbnailTiffDirectory.class);

            if (thumbnailDir != null) {
                thumbnail = thumbnailDir.getThumbnailImage();
            }

        }
        return thumbnail;
    }

    public Set<String> getAllKeywords() {

        return getKeywordSet();
    }

    public int getRotationAngle() {

        load();
        if (metadata == null) {
            return 0;
        }
        // TODO The orientation info is in TiffDirectory, should move it out of
        // ExifDirectory
        ExifDirectory exifDir = (ExifDirectory) metadata.getDirectory(TiffDirectory.class);
        if (exifDir == null) {
            return 0;
        }
        try {
            return exifDir.getAutoRotationAngle();
        } catch (MetadataException e) {
            LOG.warn("Exception trying to read rotation angle. Using 0 " + e.getMessage());
            return 0;
        }

    }

    public int getThumbnailRotationAngle() {

        load();
        if (metadata == null) {
            return 0;
        }

        if (metadata.containsDirectory(ThumbnailTiffDirectory.class)) {
            ThumbnailTiffDirectory thumbnailDir = (ThumbnailTiffDirectory) metadata.getDirectory(ThumbnailTiffDirectory.class);
            try {
                if (thumbnailDir.hasAutoRotationAngle()) {
                    return thumbnailDir.getAutoRotationAngle();
                }
            } catch (MetadataException e) {
                LOG.warn("Problem getting thumbnail rotation");
            }

        }

        return getRotationAngle();

    }

}
